layui.define(['table', 'form', 'upload', 'admin'], function (exports) {
    var $ = layui.$
        , table = layui.table
        , form = layui.form
        , upload = layui.upload
        , admin = layui.admin;

    // 专家列表
    table.render({
        elem: '#LAY-expert-manage'
        , url: '/admin/game/index_handle'
        , cols: [[
            { field: 'id', width: 80, title: 'ID', sort: true, fixed: true }
            , { field: 'name', width: 150, title: '游戏名称', fixed: true }
            , { field: 'name_en', width: 80, title: '游戏名称(en)', fixed: true }
            , {
                field: '', title: '缩略图', width: 120, templet: function (d) {
                    return '<img style="display: inline-block;height: 100%;" src= "' + d.thumb + '" layadmin-event="iconPreview" value= "' + d.thumb + '">';
                }
            }
            , { field: 'sort', title: '排序', width: 100 }
            , { field: 'url', title: '游戏链接', width: 500 },
            {
                title: "操作",
                width: 150,
                align: "right",
                fixed: "right",
                toolbar: "#table-expertlist",
            },
        ]]
        , page: true
        , limit: 20
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true,
    });

    //监听工具条
    table.on('tool(LAY-expert-manage)', function (obj) {
        if (obj.event === 'edit') {
            var index = layer.open({
                type: 2
                , title: '编辑关卡奖励'
                , content: '/admin/game/edit?id=' + obj.data.id
                , maxmin: true
                , area: ['900px', '500px']
            });
        }

        if (obj.event === 'delete') {
            layer.confirm('确定要删除吗？', function (index) {
                admin.req({
                    url: '/admin/game/delete?id=' + obj.data.id
                    , data: obj.field
                    , success: function (res) {
                        if (res.code == 0) {
                            layer.closeAll("loading");
                            window.location.reload();
                            table.reload('LAY-expert-manage');
                        }
                    },
                    complete: function () {
                        layer.closeAll('loading');
                    }
                });
            });
            return false;
        }

    });

    form.on('submit(LAY-signin-add)', function (obj) {
        layer.open({
            type: 2
            , title: '添加奖励关卡'
            , content: '/admin/game/add'
            , maxmin: true
            , area: ['900px', '500px']
        });
    });

    //上传头像
    var iconSrc = $('#LAY_iconImgSrc');
    var iconPreview = $('#coverImgPreview');
    upload.render({
        url: '/admin/index/noOperation'
        , elem: '#LAY_iconImgUpload'
        , auto: true
        , choose: function (obj) {
            layer.load();
            var choosefile;
            obj.preview(function (index, file, result) {
                choosefile = file;
            });
            admin.req({
                url: '/admin/index/signForCos'
                , success: function (res) {
                    if (res.code == 0) {
                        var cos = new COS({
                            getAuthorization: function (options, callback) {
                                var credentials = res.data.credentials;
                                callback({
                                    TmpSecretId: credentials.tmpSecretId,
                                    TmpSecretKey: credentials.tmpSecretKey,
                                    XCosSecurityToken: credentials.sessionToken,
                                    ExpiredTime: res.data.expiredTime
                                });
                            }
                        });
                        cos.putObject({
                            Bucket: res.data.bucket,
                            Region: res.data.region,
                            Key: 'images/' + res.data.filename + choosefile.name,
                            Body: choosefile,
                        }, function (err, data) {
                            layer.closeAll('loading');
                            if (err) {
                                console.log(err);
                                layer.msg("上传失败", { icon: 5 });
                            } else {
                                if (data.statusCode == 200) {
                                    iconSrc.val("https://" + data.Location);
                                    iconPreview.attr("value", iconSrc.val());
                                } else {
                                    layer.msg("图片上传失败", { icon: 5 });
                                }
                            }
                        });
                    } else {
                        layer.closeAll('loading');
                        layer.msg(res.msg, { icon: 5 });
                    }
                },
                complete: function () {
                    layer.closeAll('loading');
                }
            })
        }
    });

    //查看头像
    admin.events.iconPreview = function (othis) {
        var src = othis.attr("value");
        if (!src) {
            src = iconSrc.val();
        }
        layer.photos({
            photos: {
                "title": "查看" //相册标题
                , "data": [{
                    "src": src //原图地址
                }]
            }
            , shade: 0.01
            , closeBtn: 1
            , anim: 5
        });
    };

    table.render({
        elem: '#LAY-fruit-flow'
        , url: '/admin/game/fruit_flow_handle'
        , cols: [[
            { field: 'id', width: 80, title: 'ID', sort: true, fixed: true }
            , { field: 'user_id', width: 150, title: '用户ID', fixed: true }
            , { field: 'nickname', width: 150, title: '用户昵称', fixed: true }
            , { field: 'bet', width: 100, title: '押注', fixed: true }
            , { field: 'award_amount', width: 100, title: '中奖', fixed: true }
            , { field: 'type', width: 120, title: '类型', fixed: true }
            , { field: 'before_balance', width: 80, title: '帐变前', fixed: true }
            , { field: 'after_balance', width: 80, title: '帐变后', fixed: true }
            , { field: 'time', title: '时间', width: 200 }
        ]]
        , page: true
        , limit: 20
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true
    });

    table.render({
        elem: '#LAY-dice-flow'
        , url: '/admin/game/dice_flow_handle'
        , cols: [[
            { field: 'id', width: 70, title: 'ID', sort: true}
            , { field: 'user_id', width: 90, title: '用户ID'}
            , { field: 'nickname', width: 120, title: '用户昵称'}
            , { field: 'time', title: '时间', width: 180,}
            , { field: 'tag', width: 80, title: '模式',  templet: function(d){
                return d.tag ? '自动' : '单次';
            }} 
            , { field: 'choices', width: 100, title: '选择范围',  templet: function(d) {
                return d.is_roll_down? '[1 - '+ d.choices +']' : '['+ d.choices +' - 100]'
            } } 
            , { field: 'bet_num', width: 120, title: '下注金额', templet: function(d) {
                return d.bet_num / 100
            }} 
            , { field: 'roll_num', width: 120, title: '掷奖结果'} 
            , { field: 'odds', width: 100, title: '赔率'} 
            , { field: 'is_reward', width: 100, title: '是否中奖', templet: function(d){
                return `<span style="color: ${d.is_reward ? '#009688' : 'red'};">${d.is_reward ? '是' : '否'}</span>`;
            } } 
            , { field: 'reward_num', width: 100, title: '中奖金额', templet: function(d) {
                return d.reward_num / 100
            }} 
            , { field: 'award_amount', width: 100, title: '净入账', templet: function(d) {
                return d.award_amount / 100
            }}
            , { field: 'before_balance', width: 100, title: '帐变前', templet: function(d) {
                return d.before_balance / 100
            }}
            , { field: 'after_balance', minWidth: 100, title: '帐变后', templet: function(d) {
                return d.after_balance / 100
            }}
        ]]
        , page: true
        , limit: 20
        , height: 'full-140'
        , text: '对不起，加载出现异常！'
        , even: true
        , autoCol: true
        , done: function(res) {
            $("#total_bet_num").text(res.total_bet_num / 100 || 0);
            $("#total_award_amount").text(res.total_award_amount / 100 || 0);
        }
    });

    exports('game', {})
});


function formatTimeStamp(time_stamp) {
    const time = new Date(time_stamp * 1000);
    const Y = time.getFullYear();
    const M = (time.getMonth() + 1).toString().padStart(2, "0");
    const D = time.getDate().toString().padStart(2, "0");
    const h = time.getHours().toString().padStart(2, "0");
    const m = time.getMinutes().toString().padStart(2, "0");
    const s = time.getSeconds().toString().padStart(2, "0");
    return `${Y}-${M}-${D} ${h}:${m}:${s}`;
}